package com.magupe.im.web.db.service.h2;

import com.magupe.im.web.db.utils.ResultSetUtil;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class H2DataSource {

    private final H2DataPool pool;

    public H2DataSource(){
        this.pool = new H2DataPool(10);
    }

    public <T> List<T> getResultSetWithCollection(Class<T> clazz, String sql){
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        try{
            conn = pool.getConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            return ResultSetUtil.resultToPojo(rs, clazz);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if(null != rs) pool.releaseRs(rs);
            if(null != statement) pool.releaseStmt(statement);
            if(null != conn) pool.releaseConnection(conn);
        }
        return null;
    }

    public void execute(String sql){
        Connection conn = null;
        Statement statement = null;
        try{
            conn = pool.getConnection();
            statement = conn.createStatement();
            statement.execute(sql);
        } catch (SQLException e){
            e.printStackTrace();
        } finally {
            if(null != statement) pool.releaseStmt(statement);
            if(null != pool) pool.releaseConnection(conn);
        }
    }

    public void executeUpdate(String sql) {
        Connection conn = null;
        Statement statement = null;
        try{
            conn = pool.getConnection();
            statement = conn.createStatement();
            statement.executeUpdate(sql);
        } catch (SQLException e){
            e.printStackTrace();
        } finally {
            if(null != statement) pool.releaseStmt(statement);
            if(null != conn) pool.releaseConnection(conn);
        }
    }
}
